package com.bbcare.followup.plat.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import com.bbcare.comm.AppException;
import com.bbcare.comm.Constants;
import com.bbcare.comm.ErrorCode;
import com.bbcare.comm.ResultModel;
import com.bbcare.followup.plat.service.IKailiService;


/**
 * 凯里体检业务。
 */
@Controller
@RequestMapping("/kaili")
public class KailiController {
    private final static Logger logger = Logger.getLogger(KailiController.class);

    @Autowired
    private IKailiService kailiService;

    /**
     * 模糊查询幼儿园名称。
     * @param request
     * @param arg
     * @return
     * @throws Exception
     */
    @PostMapping("/queryNursery")
    @ResponseBody
    public ResultModel queryNursery(HttpServletRequest request, @RequestBody String arg) throws Exception {
        logger.info("++++queryNursery()----arg==" + arg.toString());

        JSONObject jsonArg = null;
        try {
            jsonArg = JSON.parseObject(arg);
        } catch (Exception ex) {
            logger.error(ex);
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_FORMAT_ERROR, "入参格式错误，非json格式！"));
        }

        JSONObject jsonData = jsonArg.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD);
        if (null == jsonData) {
            // 前台必须传data节点，否则报错返回
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！"));
        }

        final String nameLike   = jsonData.getString("nameLike");
        if (StringUtils.isBlank(nameLike)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，未传入nameLike或值为空！"));
        }

        final Map<String,Object> retMap   = kailiService.queryNurseryList(nameLike);
        return new ResultModel(retMap);
    }

    /**
     * 增加一个新的幼儿园。
     * @param request
     * @param arg
     * @return
     * @throws Exception
     */
    @PostMapping("/insertNursery")
    @ResponseBody
    public ResultModel insertNursery(HttpServletRequest request, @RequestBody String arg) throws Exception {
        logger.info("++++insertNursery()----arg==" + arg.toString());

        JSONObject jsonArg = null;
        try {
            jsonArg = JSON.parseObject(arg);
        } catch (Exception ex) {
            logger.error(ex);
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_FORMAT_ERROR, "入参格式错误，非json格式！"));
        }

        JSONObject jsonData = jsonArg.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD);
        if (null == jsonData) {
            // 前台必须传data节点，否则报错返回
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！"));
        }

        Map<String,Object> paraMap  = new HashMap<>();
        final String name   = jsonData.getString("name");
/*
        final String street = jsonData.getString("street");
        final String address= jsonData.getString("address");
        final String xingzhi= jsonData.getString("xingzhi");    //性质：公办/民办。
*/
//        if (StringUtils.isBlank(name) || StringUtils.isBlank(street) || StringUtils.isBlank(address) || StringUtils.isBlank(xingzhi)) {
        if (StringUtils.isBlank(name)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，未传入name/street/address/xingzhi或值为空！"));
        } else {
            paraMap.put("name",     name);
/*
            paraMap.put("street",   street);
            paraMap.put("address",  address);
            paraMap.put("xingzhi",  xingzhi);
*/
        }

        final int insRet    = kailiService.insertNursery(paraMap);
        Map<String,Object> retMap   = new HashMap<>();
        if (1 == insRet)    {
            retMap.put("msg",   "已成功增加了一个新的幼儿园");
        } else {
            retMap.put("msg",   "增加幼儿园失败，请联系后台管理人员！");
        }
        return new ResultModel(retMap);
    }

    /**
     * 查询1级指标。
     *
     * @param request
     * @param arg
     * @return
     * @throws Exception
     */
    @PostMapping("/queryIndex1")
    @ResponseBody
    public ResultModel queryIndex1(HttpServletRequest request, @RequestBody String arg) throws Exception {
        logger.info("++++queryIndex1()----arg==" + arg.toString());
        final List<Map<String, Object>> retList = kailiService.queryChildIndex1();
        return new ResultModel(retList);
    }

    /**
     * 查询2级指标。
     * @param request
     * @param arg
     * @return
     * @throws Exception
     */
    @PostMapping("/queryIndex2")
    @ResponseBody
    public ResultModel queryIndex2(HttpServletRequest request, @RequestBody String arg) throws Exception {
        logger.info("++++queryIndex2()----arg==" + arg.toString());

        JSONObject jsonArg = null;
        try {
            jsonArg = JSON.parseObject(arg);
        } catch (Exception ex) {
            logger.error(ex);
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_FORMAT_ERROR, "入参格式错误，非json格式！"));
        }

        JSONObject jsonData = jsonArg.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD);
        if (null == jsonData) {
            // 前台必须传data节点，否则报错返回
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！"));
        }

        final String indexId   = jsonData.getString("indexId");
        if (StringUtils.isBlank(indexId)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，未传入indexId或值为空！"));
        }

        final List<Map<String,String>> index2List= kailiService.queryChildIndex2(indexId);
        return new ResultModel(index2List);
    }

    /**
     * 查询体检儿童列表。
     * @param request
     * @param arg
     * @return
     * @throws Exception
     */
    @PostMapping("/queryChildren")
    @ResponseBody
    public ResultModel query(HttpServletRequest request, @RequestBody String arg) throws Exception {
        logger.info("++++query()----arg==" + arg.toString());

        JSONObject jsonArg = null;
        try {
            jsonArg = JSON.parseObject(arg);
        } catch (Exception ex) {
            logger.error(ex);
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_FORMAT_ERROR, "入参格式错误，非json格式！"));
        }

        JSONObject jsonData = jsonArg.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD);
        if (null == jsonData) {
            // 前台必须传data节点，否则报错返回
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！"));
        }

        Map<String,Object> paraMap  = new HashMap<>();
        //体检开始日期、结束日期。
        final String startDate  = jsonData.getString("startDate");
        final String endDate    = jsonData.getString("endDate");
        //一级指标和二级指标。
        final String index1     = jsonData.getString("index1");
        final String index2     = jsonData.getString("index2");
        //分页参数。
        final String pageNo     = jsonData.getString("pageNo");
        final String pageSize   = jsonData.getString("pageSize");

        if (StringUtils.isNotBlank(index1) && StringUtils.isBlank(index2))  {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无index2节点或值为空！"));
        }
        if (StringUtils.isBlank(index1) && StringUtils.isNotBlank(index2))  {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无index1节点或值为空！"));
        }

        if (StringUtils.isNotBlank(startDate)) {
            paraMap.put("startDate",    startDate);
        } else {
            paraMap.put("startDate",    "");
        }
        if (StringUtils.isNotBlank(endDate)) {
            paraMap.put("endDate",  endDate);
        } else {
            paraMap.put("endDate",  "");
        }
        if (StringUtils.isNotBlank(index1)) {
            paraMap.put("index1",   index1);
            paraMap.put("index2",   index2);
        } else {
            paraMap.put("index1",   "");
            paraMap.put("index2",   "");
        }

        if (StringUtils.isNotBlank(pageNo))   {
            paraMap.put("pageNo", Integer.valueOf(pageNo));
        }
        if (StringUtils.isNotBlank(pageSize))   {
            paraMap.put("pageSize", Integer.valueOf(pageSize));
        }

        final Map<String,Object> resultMap  = kailiService.queryBabyList(paraMap);
        return new ResultModel(resultMap);
    }

    @ResponseBody
    @PostMapping("/center")
    public ResultModel<Map> center(@RequestBody String arg, HttpServletRequest request) throws Exception {
        logger.info("++++center() arg:" + arg);

        Map<String,Object> paraMap  = new HashMap<>();
        return new ResultModel<Map>(kailiService.center(paraMap));
    }

    @ResponseBody
    @PostMapping("/bottom")
    public ResultModel<Map> bottom(@RequestBody String arg, HttpServletRequest request) throws Exception {
        logger.info("++++bottom() arg:" + arg);

        Map<String,Object> paraMap  = new HashMap<>();
        return new ResultModel<Map>(kailiService.bottom(paraMap));
    }

    @ResponseBody
    @PostMapping("/left")
    public ResultModel<Map> left(@RequestBody String arg, HttpServletRequest request) throws Exception {
        logger.info("++++left() arg:" + arg);

        Map<String,Object> paraMap  = new HashMap<>();
        return new ResultModel<Map>(kailiService.left(paraMap));
    }

    @ResponseBody
    @PostMapping("/right")
    public ResultModel<Map> right(@RequestBody String arg, HttpServletRequest request) throws Exception {
        logger.info("++++right() arg:" + arg);

        Map<String,Object> paraMap  = new HashMap<>();
        return new ResultModel<Map>(kailiService.right(paraMap));
    }
}